#-*- coding: utf-8 -*-

#This file is part of pyLot library.
#
# pyLot is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pyLot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pyLot.  If not, see <http://www.gnu.org/licenses/>.

__author__ = u'Pierre Puiseux, Guillaume Baty'
__copyright__ = u"Copyright 2011-2012 (C) andheo, Université de Pau et des Pays de l'Adour"
__credits__ = [u'Pierre Puiseux', u'Guillaume Baty']
__license__ = "GNU Lesser General Public License"

__all__ = ['PyLotDict']

try :
  from collections import OrderedDict
except ImportError :
  from pyLotExternal.odict import odict as OrderedDict

from _pylot.minimal.utils import check_type

class PyLotDict(OrderedDict):
  """
  Based on OrderedDict, adds path selection and index selection :
  
  
  **paths**
  >>> d = PyLotDict()
  >>> d['a/b/c'] = True
  >>> d['a']['b']['c']
  True
  >>> d['a/b']['c']
  True
  >>> d['a/b/c']
  True
  
  **indices**
  >>> d['a/b'][0]
  True
  
  Limitation :
    To avoid problem between indices/keys and path/keys,
    only unicode/str keys without '/' are allowed
  """

  def __getitem__(self, key):
    if isinstance(key, basestring):
      try:
        return OrderedDict.__getitem__(self, key)
      except KeyError, error :
        path = key.split(u'/')
        if len(path) >= 2 :
          root = self.__getitem__(path[0])
          child = u'/'.join(path[1:])
          return root[child]
        else :
          raise error
    elif isinstance(key, int):
      return OrderedDict.__getitem__(self, self.keys()[key])
    else :
      raise check_type(u'key', key, [int, unicode])

  def __setitem__(self, key, value):
    if isinstance(key, basestring) :
      path = key.split(u'/')
      if len(path) >= 2 :
        child = u'/'.join(path[1:])
        try :
          root = self[path[0]]
        except KeyError :
          root = self[path[0]] = self.__class__()
        root.__setitem__(child, value)
      else :
        OrderedDict.__setitem__(self, key, value)
    else :
      raise check_type(u'key', key, [int, unicode])

  def __copy__(self):
    import copy
    data = self.__class__()
    for k, v in self.items():
      data[k] = copy.copy(v)
    return data

  def copy(self):
    return self.__copy__()

  def new(self):
    return self.__class__()

  def sample(self):
    return u"""data[u'block1/group1/val1'] = 5
data[u'block1'][u'group1'][u'val2'] = True
data[u'block1'][u'group1'][u'val3'] = 10
"""

  def toPyCode(self):
    return repr(self)
